package com.cgwx.aop;

import com.alibaba.fastjson.JSONObject;
import com.cgwx.aop.result.ResultUtil;
import com.cgwx.data.dto.UserInfo;
import com.cgwx.mapper.UsUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@Component
@Aspect
@Slf4j
public class AuthenticationImpl {
    private static RestTemplate restTemplate;
    private final static String qualityReportAuth = "QualityReportAuth";
    private final static String purchaseRequisitionAuth = "PurchaseRequisitionAuth";

    @Resource
    UsUserMapper usUserMapper;
//    @Autowired
//    PjProjectInfoMapper pjProjectInfoMapper;
//    @Autowired
//    PjProjectMemberMapper pjProjectMemberMapper;

    @Value("${getUser}")
    private String getUser;//文件这里使用的是public

    @Resource
    public void setRestTemplate(RestTemplate restTemplate){
        AuthenticationImpl.restTemplate =restTemplate;
    }

    List<String> getCookiesString(Cookie[] cookies){
        if(cookies==null)return null;
        List<String> cookiesString=new ArrayList<>();
        for(Cookie  cookie:cookies){
            cookiesString.add(cookie.getName() + "=" + cookie.getValue());
        }
        return cookiesString;
    }

    @Pointcut("@annotation(com.cgwx.aop.GetUserInfo)")
    public void pointCut(){
    }
    @Around(value = "pointCut()")
    public Object around( ProceedingJoinPoint joinPoint) throws Throwable {
        //获取切入点参数
        MethodSignature msg = (MethodSignature)joinPoint.getSignature();
        String[] paramName = msg.getParameterNames();

        List<String> paramNameList = Arrays.asList(paramName);
        Integer pos=paramNameList.indexOf("userInfo");
        //获取传入的参数
        Object[] args = joinPoint.getArgs();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest();
        log.info("{}: {}", Timestamp.valueOf(LocalDateTime.now()), request.getRequestURI());

        HttpHeaders requestHeaders = new HttpHeaders();
        //获得请求头
        List<String> cookies=getCookiesString(request.getCookies());

        if(cookies==null)
        {
            log.warn("around没有请求头");
            return  joinPoint.proceed();
        }

        try{
            requestHeaders.put("Cookie", cookies);
            HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
            //调用用户服务获取userId
            JSONObject result=restTemplate.exchange(getUser, HttpMethod.POST,requestEntity,JSONObject.class).getBody();
            //System.out.println("用户信息："+result.toJSONString());
            //LOGGER.info("user:"+result.getJSONObject("data").getString("account"));
            String userName=result.getJSONObject("data").getString("name");
            String userId=result.getJSONObject("data").getString("account");
//            String dept=result.getJSONObject("data").getString("deptId");
//            String roleName=result.getJSONObject("data").getString("roleId");
            String chargeDept= usUserMapper.queryChargeDeptByUserId(userId);
//            UserInfo userInfo=new UserInfo( userName,  userId,roleName,dept,chargeDept);//之上是线上
            String deptId=result.getJSONObject("data").getString("deptId");
            String roleId=result.getJSONObject("data").getString("roleId");
            String deptName = result.getJSONObject("data").getString("deptName");
            String roleName = result.getJSONObject("data").getString("roleName");
            String groupIds = result.getJSONObject("data").getString("groupIds");
            String groupNames = result.getJSONObject("data").getString("groupNames");
            UserInfo userInfo=new UserInfo(userName,userId,deptId,roleId,deptName,roleName,groupIds,groupNames,chargeDept);
            args[pos]=userInfo;
            //修改参数后调用切入点函数

        }
        catch (Exception e){
            log.warn(e.getMessage());
//            LOGGER.error("连接用户服务失败:"+e.getMessage());
//            e.printStackTrace();
            return ResultUtil.error(501,"用户服务连接失败");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return ResultUtil.error(500,"");
        }
        return joinPoint.proceed(args);
    }

}
